/**
 *	每月28号执行，检索下个月的销售月计划，
 *	条件：所有人的简档=销售部分销销售员、销售部分销经理/主管、销售部直销销售员、销售部直销经理/主管，
 *	如果没有找到下个月的销售月计划，新建任务提醒
 *	created by Harry 2017-01-10 20:14:21
 */
global class CheckSalesMonthlyPlanSchedule implements Schedulable {
    global void execute(SchedulableContext sc) {
    	Date today = Date.today();
    	//下个月的今天
    	Date nextMonth = today.addMonths(1);

    	Set<String> profileSet = new Set<String>();
    	// {
    	// 	'销售部分销销售员',
    	// 	'销售部分销经理/主管',
    	// 	'销售部直销经理/主管',
    	// 	'销售部直销销售员'};

    	String profileStr = Label.ProfilesofMonthlyPlan;
    	List<String> profileList = profileStr.split(',');
    	if(null != profileList){
    		profileSet.addAll(profileList);
    	}

    	System.debug(LoggingLevel.INFO, '*** profileSet: ' + profileSet);

	    // 缓存，用来存储[用户]和[月计划]的ID映射
	    Map<Id,Id> userSMPMap = new Map<Id,Id>();

	    Map<Id,User> users = new Map<Id,User>([
	    	SELECT Id,Profile.Name
	    	FROM User WHERE Profile.Name IN : profileSet AND IsActive = true]);
	    
	    System.debug(LoggingLevel.INFO, '*** : ' + nextMonth.year()+'@@@'+nextMonth.month());

        Map<Id,SalesMonthPlan__c> SalesMonthPlans = new Map<Id,SalesMonthPlan__c>([
        	SELECT Id,Owner.Profile.Name 
        	FROM SalesMonthPlan__c 
        	WHERE Year__c =: String.valueOf(nextMonth.year()) 
	        	AND Month__c =: String.valueof(nextMonth.month()) 
	        	AND Owner.Profile.Name IN :profileSet]);
        //将所有符合条件的[用户]ID存入缓存，其对应的[月计划]ID初始化为null
		for(Id id : users.keySet()){
	    	userSMPMap.put(id, null);
	    }
	    //将有填写了[月计划]的记录ID存入缓存
	    for(Id id : SalesMonthPlans.keySet()){
	    	SalesMonthPlan__c SMP = SalesMonthPlans.get(id);
	    	userSMPMap.put(SMP.OwnerId, id);
	    }
	    //缓存中[月计划]ID仍为null的既是没有填写[月计划]的用户，需要新建任务提醒
	    List<Task> taskList = new List<Task>();
	    for(Id userId :userSMPMap.keySet()){
	    	Id SMPId = userSMPMap.get(userId);
	    	if(null == SMPId){
	    		Task t = new Task();
	        	t.ActivityDate=Date.today();
	        	t.OwnerId=userId;
	        	t.Subject='请及时填写下个月计划';
	        	taskList.add(t);
	        	System.debug(LoggingLevel.INFO, '*** 没填写下月计划的用户ID: ' + userId);
	    	}
	    }
	    insert taskList;
    }
}